//vuex状态管理
const store = new Vuex.Store({
    state: {
        selectedEmployees: []
    },
    mutations: {
        updateEmployees:function(state,param) {
            //判断员工是否已选
            for(var i=0;i<state.selectedEmployees.length;i++){
                if(state.selectedEmployees[i].id == param.id){
                    state.selectedEmployees.splice(i,1) //如果有相同员工id，则删除该员工
                    return false
                }
            }
            state.selectedEmployees.push(param);
        },
        deleteEmployee:function(state,param){
            //clearAll为true时选择员工置空
            if(!!param.clearAll){
                state.selectedEmployees = [];
                return false;
            }
            //删除选中员工
            for(var i=0;i<state.selectedEmployees.length;i++){
                if(state.selectedEmployees[i].id == param.id){
                    state.selectedEmployees.splice(i,1)
                    break
                }
            }
            return false;
        }
    }
})
//vue实例初始化
var customerApp = new Vue({
    el:'#main',
    data:{
        sLoading: true, //LOADING
        custType: 0, //记录类型 0 意向 1 签约 2 潜在
        userInfo: {}, //当前登陆用户名信息
        currentTime: -1, //当前时间辍
        formData: {
            records: [],
        },//渲染数据
        pageSizeSelected: -1,//每页选择条数
        filterParameters: {
            searchKey: '', //搜索关键字
            provinceCode: -1, //省编码
            cityCode: -1, //市编码
            countyCode: -1, //区编码
            startDate: '', //搜索开始的日期(格式:2017-8-12)
            endDate: '', //搜索开始的日期(格式:2017-8-12)
            current: 1, //当前页码默认为0
            pageSize: 10, //每页查询条数默认10条
            intentionStatus: -1 //意向状态
        },
        /*模态框显示隐藏*/
        modal: {
            assign: false, //指派
            followRecord: false, //添加跟进记录
            certificate: false, //添加证照
            employee: false, //选择员工
            abutment: false, //对接人
            contact: false, //添加联系人
            intention: false, //添加到意向客户
        },
        //客户暂存区
        custItemStorage:{},
        //跟进记录
        followInfo:{
            id: -1, //添加无 更新有
            custId: -1, //客户id
            customerName: '', //客户名称
            customerType: 0, //客户类型 0 企业
            custConcats: [], //对接人id集合
            followIds: [], //跟进人集合
            followDetail: '', //跟进详情
            followReasonId: -1, //跟进事由id 来源数据词典
            followType:-1, //跟进类型id 来源数据词典
            followTime: -1, //跟进时间
            types: 0, //跟进记录类型 0 意向 1 签约 2 潜在
            //front add
            selectedContactNames: '', //选中的联系人
            selectedContactInfo: [], //选中联系人信息
            allContacts: [], //当前客户的联系人信息
        },
        followRecord:{
            records: [],
        },
        followPage:{
            pageSizeSelected_follow: -1,//每页选择条数
            filterParameters: {
                id: -1, //客户id
                types: 0, //跟进记录类型 0 意向 1 签约 2 潜在
                current: 1, //当前页码默认为0
                pageSize: 10, //每页查询条数默认10条
            }
        },
        //指派记录
        assignRecord:{
            records: [],
        },
        assignPage:{
            pageSizeSelected_assign: -1,//每页选择条数
            filterParameters: {
                id: -1, //意向id
                types: 0, //指派记录类型 0 意向 1 签约 2 潜在
                current: 1, //当前页码默认为0
                pageSize: 10, //每页查询条数默认10条
            }
        },
        /*（选择员工）部门树形数据*/
        departTree: {
            originalData:{}, //获取原始数据
            msg:[],  //存储数据结构改变后的数据
            show: true, //显示隐藏
        },
        departTreeSearchKey: '', //搜索内容
        employeeResult: [], //员工搜索结果
        finalSelectedEmployees: [], //最终显示的员工数据
        /*全选反选*/
        checkAll: false, //默认全不选
        checkedCustIds: [], //指派选择框
        checkboxData: [], //存储当前页所有客户id（除去"无需指派"）
        checkboxDataForDelete: [], //存储当前页所有客户id
        //客户处理（详情+编辑）
        handle: {
            display: false, //显示隐藏
            state: 0, // 0 详情  1 编辑
            data: {
                //意向客户
                intentionContent:{
                    //intentionType: 0,//意向类型 0添加意向 1添加我的意向
                    id: -1, //更新意向信息
                    //custId: -1, //客户id （查询企业返回）
                    //custQueryId: -1,//客户企查查记录id （查询企业返回）
                    contactType: 'ctT10', //联系人类型(意向联系人 )数据词典编码 默认ctT10
                    businessLabelIds: [],//业务标签
                    customerType:0,//客户类型  0 企业
                    customerName: '',//客户名称
                    gender: 0,//性别
                    contactName: '',//联系人
                    contactPhone: '',//联系电话
                    provinceCode: -1,//省编码
                    cityCode: -1,//市编码
                    countyCode: -1,//区编码
                    detailAddr: '',//详细地址
                    businessTags: [],//全部意向标签
                    tagAttribute: [], //选中的意向标签
                    citypickerAddress: '', //后台返回的省市区地址
                    custIntentionDetail: '', //客户意向详情
                }
            }
        },
        //获取当前客户的联系人
        contactsData:[],
        //数据词典
        dictData:{
            contactsType: [], //联系人类型
            licenseType: [], //证照类型
            followupWay: [], //跟进方式
            followupReason: [], //跟进事由
        },
        //请求
        req: {
            //添加联系人
            addContact: {
                contactType: '', //联系人类型
                contactName: '', //姓名
                gender: 0, //性别
                phoneNumber: '', //联系电话
                email: '', //电子邮箱
                wechat: '', //微信
                qq: '', //QQ
                birthday: '', //生日
                gongLiFlag: 0, //公农历
                position: '', //职位
                remark: '', //备注
                types: 0, //0：意向，1:签约 2 潜在
            },
            //指派
            assign:{
                assignRemark: '', //指派备注
            },
            //添加意向客户（弹窗）
            intentionContent:{
                intentionType: 0,//意向类型 0添加意向 1添加我的意向
                id: -1, //添加有 更新无
                custId: -1, //客户id （查询企业返回）
                custQueryId: -1,//客户企查查记录id （查询企业返回）
                contactType: 'ctT10', //联系人类型(意向联系人 )数据词典编码 默认ctT10
                businessLabelIds: [],//业务标签
                customerType:0,//客户类型  0 企业
                customerName: '',//客户名称
                gender: 0,//性别
                contactId: -1,//联系人Id
                contactName: '',//联系人
                contactPhone: '',//联系电话
                provinceCode: -1,//省编码
                cityCode: -1,//市编码
                countyCode: -1,//区编码
                detailAddr: '',//详细地址
                businessTags: [],//全部意向标签
                tagAttribute: [], //选中的意向标签
                citypickerAddress: '', //后台返回的省市区地址
                custIntentionDetail: '', //客户意向详情
            }
        },
        //企业查询
        queryEnterprise:{
            display: false,
            result: {
                hasResult: false, //是否查到结果
            }
        },
        //联系人(客户对接人)
        queryContacts:{
            display: false,
            result: []
        },
        //富文本
        ue_modal:{},
        ue_edit:{},
        isFirstCreateUE: true, //handle是否第一次加载富文本
    },
    store:store,
    components:{
        /*（选择员工）部门树形组件*/
        tree: {
            name: 'tc',
            template: '<section class="visible transition">\
    <section class="title" @click="loadEmployees(msg.id,msg.children)">\
    <i class="dropdown icon"></i>\
    <a>{{msg.name}}</a>\
</section>\
<section class="content">\
    <div v-for="e in employeesData" class="transition employeeItem" :data-id="e.id" @click="selectEmployeeData(e.id,e.employeeName)">{{e.employeeName}}\
    <div class="mask-prevent"></div>\
    <div class="ui checkbox fr">\
    <input type="checkbox" v-model="selectedEmployees" :value="e.id">\
    <label></label>\
    </div>\
    </div>\
    <tc v-for="v in msg.children" :msg="v"></tc>\
</section>\
</section>',
            props: ['msg'],
            components: {

            },
            data:function(){
                return {
                    employeesData: [] //员工数据
                }
            },
            computed:{
                selectedEmployees:function(){
                    var result = [];
                    this.$store.state.selectedEmployees.forEach(function(obj){
                        result.push(obj.id)
                    })
                    return result
                }
            },
            methods:{
                //按部门id加载员工表
                loadEmployees:function(id,arr){
                    var self = this;
                    if(self.employeesData.length == 0 ){
                        Customer.axiosRequest(Customer.interface.queryEmployeeJson,{
                            departmentId: id
                        },function(result){
                            if(result.code == 0){
                                self.employeesData = result.data;
                            }
                        },{
                            type:'post',
                        })
                    }else{
                        return false
                    }
                },
                //选择员工
                selectEmployeeData:function(id,name){
                    //业务限制人数
                    var selectedNum = customerApp.$store.state.selectedEmployees.length;
                    if(!!customerApp.limitedNum(selectedNum,id)){
                        var transParam = {
                            id: id,
                            name: name
                        }
                        store.commit('updateEmployees',transParam)
                    }
                }
            }
        }
    },
    filters:{
        //（选择员工或联系人）确认或取消后的显示过滤
        showName:function(arr){
            if(arr.length == 0) return ''
            var result = '';
            for(var i=0;i<arr.length;i++){
                result += arr[i].name;
                result = i == arr.length-1 ? result : result + '、';
            }
            return result
        },
        //转时间辍为（格式2018-01-01）
        dateFormat:function(time,mode){
            /*Arg Guide
             @ time 时间辍
             */
            if (time == null) {
                return '';
            }
            var date = new Date(time);
            var year = date.getFullYear();
            var month = date.getMonth() + 1 >9 ? date.getMonth() + 1 : '0'+ (date.getMonth() + 1);
            var date = date.getDate() >9 ? date.getDate() : '0' + date.getDate();
            if(mode == 'm1'){
                //返回当前月第一天
                var date = '01';
            }
            return year + '-' + month + '-' + date
        },
        //限制字段长度
        limitlength:function(value,num){
            /*Arg Guide
             @ value 字符串
             @ num 限制字段长度
             */
            if(typeof value != 'string' || typeof num != 'number'){
                return;
            }
            return value.slice(0,num)
        }
    },
    created:function(){
        var self = this;
        //获取查询页面获取到的ID
        var intentionId = window.localStorage.getItem('intentionId');
        window.localStorage.removeItem('intentionId');//清空id数据
        if(!!intentionId){
            //根据id获取意向详情
            self.handleContent(parseInt(intentionId),0);
        }
    },
    /*数据渲染完毕调用*/
    mounted:function(){
        this.init();
        this.$nextTick(function(){
            var self = this;
            //时间控件
            wzERP.Common.singleDate('.single-date');
            //tab切换
            var $menu = $('.tabular.menu');
            $menu.find('.item').tab();
            //ui功能开启
            $('.ui.checkbox').checkbox();
            //（获取数据词典）联系人类型
            var contactTypeUrl = Customer.interface.dictList + '?code=' + Customer.dictCode[0];
            Customer.axiosRequest(contactTypeUrl,{},function(result){
                if(result.code == 0){
                    self.dictData.contactsType = result.data;
                }
            })
            //remove loading
            setTimeout(function(){
                self.sLoading = false;
            },100)
        })
    },
    watch:{
        //监听页数变化
        pageSizeSelected:function(val){
            this.filterParameters.pageSize = parseInt(val);
            this.filterParameters.current = 1;
            this.renderMain(Customer.interface.intentionRecords,this.filterParameters);
        },
        //监听跟进记录页数变化
        'followPage.pageSizeSelected_follow':function(val){
            this.followPage.filterParameters.pageSize = parseInt(val);
            this.followPage.filterParameters.current = 1;
            this.renderFollowRecords(Customer.interface.followRecords,this.followPage.filterParameters)
        },
        //监听指派记录页数变化
        'assignPage.pageSizeSelected_assign':function(val){
            this.assignPage.filterParameters.pageSize = parseInt(val);
            this.assignPage.filterParameters.current = 1;
            this.renderAssignRecords(Customer.interface.assignRecords,this.assignPage.filterParameters)
        },
        //test
        /*filterParameters:{
            handler:function(curVal,oldVal){
                console.log(curVal,oldVal)
            },
            deep:true
        },*/
        //监听搜索栏状态变化(全部value保持-1数字)
        'filterParameters.intentionStatus':function(val){
            val = val == undefined ? -1 : val;
            this.filterParameters.intentionStatus = parseInt(val);
        },
        //（选择员工）监听员工框搜索内容
        departTreeSearchKey:function(val){
            var self = this;
            if(val == ''){
                self.departTree.show = true
            }else{
                self.departTree.show = false
                Customer.axiosRequest(Customer.interface.queryEmployeePage,{
                    searchKey: val
                },function(result){
                    self.employeeResult = result.data;
                },{
                    type: 'post'
                })
            }
        },
        checkAll:function(newVal){
            if(!!newVal){
                this.checkedCustIds = this.checkboxDataForDelete
            }else{
                this.checkedCustIds = []
            }
        },
        //选中框内容更新
        formData:{
            handler:function(val){
                this.checkboxData = [];
                this.checkboxDataForDelete = [];
                var records = val.records;
                if(records){
                    for(var i = 0;i<records.length;i++){
                        if(records[i].intentionStatus == 0 || records[i].intentionStatus == 1){
                            this.checkboxData.push(records[i].id);
                        }
                        this.checkboxDataForDelete.push(records[i].id)
                    }
                }
            },
            deep:true
        },
        //监听客户名称搜索框
        'req.intentionContent.customerName':function(val){
            if(val == ''){
                this.queryEnterprise.display = false;
            }
        },
        //打开编辑详情页面默认tab第一个
        'handle.display':function(){
            this.$nextTick(function(){
                var $menu = $('.tabular.menu');
                $menu.find('.item').tab();
                $menu.find('.item').eq(0).click();
            })
        }
    },
    computed:{
        //（选择员工）导出选择的员工
        selectedEmployees:function(){
            var result = [];
            this.$store.state.selectedEmployees.forEach(function(obj){
                result.push(obj.id)
            })
            return result
        },
        //获取当前时间辍
        currentTime:function(){
            return new Date().getTime();
        },
    },
    methods:{
        init:function(){
            var self = this;
            self.renderMain(Customer.interface.intentionRecords,self.filterParameters);
            //（选择员工）加载树形结构初始化
            self.renderDepartData();
            //test
            // this.myIntention();
            // this.intentionLabel()
            //获取当前用户信息
            self.gainCurrentUserInfo();
            //添加联系人功能初始化
            Customer.contactFunction({
                types: 0 //0：意向，1:签约 2 潜在
            },'#addContactbox', true);
        },
        //渲染客户数据
        renderMain:function(url,param){
            var self = this;
            param = param == undefined ? {} : param;
            Customer.axiosRequest(url,param,function(result){
                self.formData = result.data;
                // 分页
                layui.use(['laypage', 'layer'], function () {
                    var laypage = layui.laypage;
                    laypage({
                        cont: 'turn_page',
                        curr: result.data.current || 1,
                        pages: result.data.pages,
                        skin: '#457fe6',
                        skip: true,
                        jump: function (obj, first) {
                            if (!first) {
                                self.filterParameters.current = obj.curr;
                                self.renderMain(url,self.filterParameters);
                            }
                        }
                    });
                })
            },{
                type:'post',
                noFilter: false  //过滤掉 {}, '', -1 这三种值
            })
        },
        //渲染跟进记录数据
        renderFollowRecords:function(url,param){
            var self = this;
            param = param == undefined ? {} : param;
            console.log(param)
            Customer.axiosRequest(url,param,function(result){
                self.followRecord = result.data;
                // 分页
                layui.use(['laypage', 'layer'], function () {
                    var laypage = layui.laypage;
                    laypage({
                        cont: 'turn_page_follow',
                        curr: result.data.current || 1,
                        pages: result.data.pages,
                        skin: '#457fe6',
                        skip: true,
                        jump: function (obj, first) {
                            if (!first) {
                                self.followPage.filterParameters.current = obj.curr;
                                self.renderFollowRecords(url,self.followPage.filterParameters);
                            }
                        }
                    });
                })
            },{
                type:'post',
                noFilter: false  //过滤掉 {}, '', -1 这三种值
            })
        },
        //渲染指派记录数据
        renderAssignRecords:function(url,param){
            var self = this;
            param = param == undefined ? {} : param;
            console.log(param)
            Customer.axiosRequest(url,param,function(result){
                self.assignRecord = result.data;
                // 分页
                layui.use(['laypage', 'layer'], function () {
                    var laypage = layui.laypage;
                    laypage({
                        cont: 'turn_page_assign',
                        curr: result.data.current || 1,
                        pages: result.data.pages,
                        skin: '#457fe6',
                        skip: true,
                        jump: function (obj, first) {
                            if (!first) {
                                self.assignPage.filterParameters.current = obj.curr;
                                self.renderAssignRecords(url,self.assignPage.filterParameters);
                            }
                        }
                    });
                })
            },{
                type:'post',
                noFilter: false  //过滤掉 {}, '', -1 这三种值
            })
        },
        //清除关键词搜索内容
        removeSearchKey:function(){
            this.filterParameters.searchKey = ''
        },
        //查询
        query:function(){
            var self = this;
            var obj = VUE_UTIL.getCode(self.$refs.location);
            //更新code数据
            if(!VUE_UTIL.isObjectEmpty(obj)){
                this.filterParameters.provinceCode = obj.provinceCode == undefined ? -1 : obj.provinceCode;
                this.filterParameters.cityCode = obj.cityCode == undefined ? -1 : obj.cityCode;
                this.filterParameters.countyCode = obj.countyCode == undefined ? -1 : obj.countyCode;
            }else{
                this.filterParameters.provinceCode = '';
                this.filterParameters.cityCode = '';
                this.filterParameters.countyCode = '';
            }
            //搜索结果默认第一页
            this.filterParameters.current = 1;
            this.renderMain(Customer.interface.intentionRecords,self.filterParameters);
        },
        //获取当前用户名信息
        gainCurrentUserInfo:function(){
            var self = this;
            axios.get(Customer.interface.accountDetail).then(function(response){
                var data = response.data;
                if(data.code == 0){
                    self.userInfo = data.data;
                }
            })
        },
        //显示员工弹窗并赋值
        showEmployeeModal:function(){
            var self = this;
            self.modal.employee = true;
            self.$store.state.selectedEmployees = self.finalSelectedEmployees.slice(0);//深拷贝
            this.departTreeSearchKey = ''; //清空搜索框内容
        },
        //加载部门树形结构
        renderDepartData:function(){
            var self = this;
            var url = Customer.interface.departTree;
            Customer.axiosRequest(url,{},function(result){
                self.departTree.originalData = result.data;
                self.departTree.msg = self.transFormatToTree(self.departTree.originalData);
            },{
                type:'post'
            })
        },
        //转换为树形数据结构
        transFormatToTree:function(data){
            var obj = {};
            for(var i = 0;i<data.length;i++){
                var key = data[i]['id'];
                obj[key] = {
                    'Name': data[i]['name'].toString(),
                    'ID': data[i]['id'].toString(),
                    'ParentID': data[i]['parentId'].toString()
                }
            }
            var resultObj = convert(obj,0) //根id为0
            function convert(source,rootpid){
                var tmp={},parent,n;
                for(n in source){
                    var item=source[n];
                    if(item.ID==item.ParentID){
                        parent=item.ID;
                    }
                    if(!tmp[item.ID]){
                        tmp[item.ID]={};
                    }
                    tmp[item.ID].name=item.Name;
                    tmp[item.ID].id=item.ID;
                    if(!("children" in tmp[item.ID]))tmp[item.ID].children=[];

                    if(item.ID!=item.ParentID){
                        if(tmp[item.ParentID]){
                            tmp[item.ParentID].children.push(tmp[item.ID]);
                        }
                        else{
                            tmp[item.ParentID]={children:[tmp[item.ID]]};
                        }
                    }
                }
                return tmp[rootpid];
            }
            return resultObj.children
        },
        //（选择员工）
        selectEmployeeData:function(id,name){
            var transParam = {
                id: id,
                name: name
            }
            store.commit('updateEmployees',transParam)
        },
        //（选择员工）删除员工
        deleteEmployee:function(id,name){
            var transParam = {
                id: id,
                name: name
            }
            store.commit('deleteEmployee',transParam)
        },
        //（选择员工）确定员工
        confirmEmployees:function(){
            var self = this;
            self.modal.employee = false;
            self.finalSelectedEmployees  = self.$store.state.selectedEmployees.slice(0);//深拷贝
        },
        //点击指派
        assign:function(){
            var self = this;
            if(self.checkedCustIds.length == 0){
                layer.msg('至少选择一个客户',{time: 1000})
                return false
            }else if(self.checkedCustIds.length > 0){
                //选中的客户无需指派
                if(!Customer.hasContainElement(self.checkedCustIds,self.checkboxData)){
                    layer.msg('选中的客户无需指派',{time: 1000})
                    return false
                }
            }else{}
            //弹出指派窗口
            self.modal.assign = true
            //初始化
            //清空员工表
            store.commit('deleteEmployee',{
                clearAll: true
            })
            self.finalSelectedEmployees = [];
            self.req.assign.assignRemark = '';
        },
        //指派确认
        addAssignRecords:function(){
            var self = this;
            var param = {
                types: self.custType,
                intentionIds:self.checkedCustIds, //意向id集合
                managerIds:self.selectedEmployees, //负责人id集合
                remark:self.req.assign.assignRemark, //指派备注
            }
            //验证-S
            if(param.managerIds.length == 0){
                layer.msg('请选择指派负责人!',{time:1000})
                return false;
            }
            //验证-E
            //判断
            var arr1 = self.checkedCustIds;
            var arr2 = self.checkboxData;
            var surplusArr = Customer.getSurplusElements(self.checkboxData,self.checkboxDataForDelete);
            //判读所选的客户是否有“无需指派”
            if(Customer.hasContainElement(arr1,surplusArr)){
                var arr3 = [];
                for(var i=0;i<arr1.length;i++){
                    if(VUE_UTIL.isInArray(arr2,arr1[i])){
                        arr3.push(arr1[i])
                    }
                }
                layer.alert('无需指派的客户将被过滤，是否继续？', {
                    title: '提示信息',
                    btn: ['取消', '确认'],
                    btn1:function(index){
                        layer.close(index)
                    },
                    btn2:function(){
                        param.intentionIds = arr3;
                        console.log('被指派的客户id:'+arr3);
                        addBatchAssign()
                    }
                })
            }else{
                addBatchAssign()
            }
            function addBatchAssign(){
                axios.post(Customer.interface.addBatchAssign, param)
                    .then(function (result) {
                        var data = result.data;
                        if(data.code == 0){
                            layer.msg('指派成功!',{time:1000})
                            self.modal.assign = false;
                            self.checkAll = false;
                            //渲染
                            self.renderMain(Customer.interface.intentionRecords,self.filterParameters);
                        }else{
                            layer.msg('指派失败!',{time:1000})
                        }
                        self.checkedCustIds = [];
                    })
                    .catch(function (error) {
                        console.log(error);
                        layer.msg(error,{time:1000})
                    });
            }
        },
        //查企业
        checkEnterprises:function(){
            var self = this;
            var name = self.req.intentionContent.customerName;
            var url = Customer.interface.checkEnterprises;//查询接口
            axios.get(url,{
                params:{
                    name:name,
                    customerType: 0 //目前只有企业
                }
            }).then(function(response){
                var data = response.data;
                self.queryEnterprise.result = {}
                if(data.code == 0){
                    self.queryEnterprise.result = {
                        hasResult: true,
                        msg: self.req.intentionContent.customerName,
                        customerId: data.data.customerId,
                        enterpriseBusinessId:data.data.enterpriseBusinessId
                    }
                }else{
                    self.queryEnterprise.result = {
                        hasResult: false,
                        msg: '未查到结果！请输入公司全称！'
                    }
                }
                self.queryEnterprise.display = true;
            })
        },
        //确认企业id
        confirmEnterpriseId:function(obj){
            var self = this;
            if(!!obj.hasResult){
                self.req.intentionContent.customerName = self.queryEnterprise.result.msg;
                self.req.intentionContent.custId = self.queryEnterprise.result.customerId;
                self.req.intentionContent.custQueryId = self.queryEnterprise.result.enterpriseBusinessId;
            }
            self.queryEnterprise.display = false;
        },
        //查企业信息跳转
        queryEnterpriseInfo:function(id){
            var self = this;
            //意向详情获取企业id
            Customer.axiosRequest(Customer.interface.intentionDetail,{id:id},function(result){
                if(result.code == 0){
                        var custQueryId = result.data.custQueryId;
                        //把查询到的公司ID储存到浏览器本地，跳转的页面通过本地储存来获取ID
                        window.localStorage.setItem('companyId',custQueryId)
                        console.info('companyId',custQueryId);
                        //请求成功以后跳转页面
                        //新加的TAB ID必须从1000起步
                        //1.请求ID
                        //2.tab显示的名称
                        //3.请求的地址
                        window.parent.erpWrap.insertTab(1000, "企业详情", "/enterprise/details");
                }
            },{
                type:'post'
            });
        },
        //提交意向客户基本信息
        submissionIntention:function(handleType){
            /**
             * 请求配置项
             * @handleType
             * (1):弹窗页面
             * (0):操作页面
             * 的意向客户提交
             */
            var self=this;
            var cityEle = handleType == 0 ? 'edit_city2' : 'modal_city2';
            var obj = handleType == 0 ? self.handle.data : self.req;

            //判断是否查到企业（客户名称）
            if(obj.intentionContent.custId == -1 || obj.intentionContent.custQueryId == -1){
                layer.msg('请确认正确的客户名称',{time:1000})
                return false
            }
            //添加无 更新有
            obj.intentionContent.id = handleType == 0 ? self.custItemStorage.id : -1;
            //获取客户意向详情
            var custIntentionDetail= handleType == 0 ? self.ue_edit.getContent() : self.ue_modal.getContent();
            if (custIntentionDetail.length > 10000) {
                layer.msg('输入内容过长，请重新编辑',{time:1000})
                return false
            }
            obj.intentionContent.custIntentionDetail = custIntentionDetail;
            //获取省编码
            obj.intentionContent.provinceCode = $('#'+cityEle).data('citypicker').getCode('province')
            //获取市编码
            obj.intentionContent.cityCode = $('#'+cityEle).data('citypicker').getCode('city')
            //获取区编码
            obj.intentionContent.countyCode = $('#'+cityEle).data('citypicker').getCode('district')
            //处理业务标签
            obj.intentionContent.businessLabelIds = []
            for(var i=0;i<obj.intentionContent.tagAttribute.length;i++){
                if(!!obj.intentionContent.tagAttribute[i]){
                    var id = obj.intentionContent.businessTags[i]['id'];
                    obj.intentionContent.businessLabelIds.push(id)
                }
            }

            //验证-S
            var validateObj = obj.intentionContent;
            var validateParam = {
                'customerName': {
                    msg: '请输入客户名称',
                },
                'contactName': {
                    msg: '请输入联系人',
                },
                'contactPhone': {
                    msg: '请输入联系电话',
                    regExp: '^[0-9-]{0,20}$',
                    regExpMsg: '（联系电话）数字或-，限20字'
                },
                'cityCode': {
                    msg: '请至少选择省市区域'
                },
                'detailAddr': {
                    msg: '请输入详细地址',
                },
                'businessLabelIds': {
                    msg: '请选择业务标签',
                },
                /*'custIntentionDetail': {
                    msg: '请输入客户意向',
                },*/
            };
            if(!Customer.validate(validateObj,validateParam)){
                return false;
            }
            //验证-E

            //去掉-1,{}
            var param = {};
            var originObj = obj.intentionContent;
            for(var index in originObj) {
                if (originObj.hasOwnProperty(index)) {
                    if (JSON.stringify(originObj[index]) !== '{}' && originObj[index] !== -1 && originObj[index] != null  ) {
                        param[index] = originObj[index]
                    }
                }
            }



            //提交意向客户数据
            axios.post(Customer.interface.addOrUpdateIntentional, param).then(function (response) {
                var data = response.data;
                if(data.code == 0){
                    if(handleType == 0){
                        layer.msg('保存成功',{time:1000})
                    }else{
                        self.modal.intention = false
                        layer.msg('添加意向客户成功！',{time:1000})
                        //渲染
                        self.renderMain(Customer.interface.intentionRecords,self.filterParameters);
                    }
                }else{
                    layer.msg(data.msg,{time:1000})
                }
            })
        },
        //意向标签选项
        intentionLabel:function(handleType){
            //请求意向标签接口
            var self=this;
            var obj = handleType == 0 ? self.handle.data : self.req;
            axios.get(Customer.interface.intentionLabel).then(function (response) {
                //获取意向标签
                obj.intentionContent.businessTags=response.data.data
                for(var i=0;i<obj.intentionContent.businessTags.length;i++){
                    obj.intentionContent.tagAttribute[i] = false
                }
            })
        },
        //选择业务标签
        serviceLabel:function (index,handleType) {
            var self = this;
            var obj = handleType == 0 ? self.handle.data : self.req;
            Vue.set(obj.intentionContent.tagAttribute,index,!obj.intentionContent.tagAttribute[index])
        },
        //添加到我的意向客户
        myIntention:function (intentionType) {
            var self = this;
            self.modal.intention = true;
            //滚动到顶
            self.$nextTick(function(){
                document.getElementById('intentionModal').scrollTop = 0;
                document.getElementsByClassName('tag_options').scrollTop = 0
            })
            //意向类型切换
            self.req.intentionContent.intentionType = intentionType;
            //渲染意向标签
            self.intentionLabel(1)
            //调用省市县联动
            $('#modal_city2').citypicker('reset')
            //添加富文本
            // var ue = UE.getEditor('editor');
            //清空所有字段
            self.clearAllfields(self.req.intentionContent);
            //初始化富文本插件
            self.ue_modal = UE.getEditor('editor_modal',{
                autoFloatEnabled:false,
            });
            self.ue_modal.ready(function(){
                self.ue_modal.setContent(''); //清空富文本
            })
        },
        //跟进
        showFollowModal:function(obj){
            var self = this;
            //清空员工表
            store.commit('deleteEmployee',{
                clearAll: true
            })
            //默认为当前时间
            var followTime = document.getElementById('followTime');
            var currentTime = new Date().getTime();
            followTime.value = Customer.dateFormat(currentTime);
            // self.followInfo.followTime = new Date().getTime();
            //跟进人获取当前登录名
            self.finalSelectedEmployees = [];
            self.finalSelectedEmployees.push({
                id: self.userInfo.employId,
                name: self.userInfo.employName
            });
            self.followInfo.custId = obj.custId;
            self.followInfo.customerName = obj.customerName;
            self.followInfo.contactId = obj.contactId;

            //最终员工选择变化
            store.commit('updateEmployees',{
                id: self.userInfo.employId,
                name: self.userInfo.employName
            })
            //联系人选择
            self.followInfo.selectedContactNames = obj.contactName;
            self.updateContacts(obj.custId);
            //暂存当前客户信息
            self.custItemStorage = obj;
            //数据词典归零
            self.followInfo.followReasonId = -1;
            self.followInfo.followType = -1;
            $('#followupWay').dropdown('clear');
            $('#followupReason').dropdown('clear');
            //客户对接人置空
            self.followInfo.selectedContactInfo = [];
            //跟进详情清空
            self.followInfo.followDetail=''
            self.$nextTick(function(){
                //重新调一次时间组件
                wzERP.Common.singleDate('.single-date');
            })

            //（获取数据词典）跟进方式
            var followupWayUrl = Customer.interface.dictList + '?code=' + Customer.dictCode[2];
            Customer.axiosRequest(followupWayUrl,{},function(result){
                if(result.code == 0){
                    self.dictData.followupWay = result.data;
                }
            })
            //（获取数据词典）跟进事由
            var followupReasonUrl = Customer.interface.dictList + '?code=' + Customer.dictCode[3];
            Customer.axiosRequest(followupReasonUrl,{},function(result){
                if(result.code == 0){
                    self.dictData.followupReason = result.data;
                }
            })
            //
            self.modal.followRecord = true;
        },
        //客户对接人选择联系人
        upposition:function(item,index){
            var self = this;
            if(typeof index == 'number'){
                self.queryContacts.result.splice(index,1);
            }
            self.followInfo.selectedContactInfo.push({
                id: item.id,
                contactName: item.contactName,
                contactNumber: item.contactNumber
            });
        },
        //删掉已选择的联系人
        downposition:function(item,index){
            var self = this;
            if(typeof index == 'number'){
                self.followInfo.selectedContactInfo.splice(index,1);
            }
            self.queryContacts.result.push({
                id: item.id,
                contactName: item.contactName,
                contactNumber: item.contactNumber
            });
        },
        //显示添加联系人弹窗
        showContactModal:function(){
            var self = this;
            self.modal.contact = true;
            self.clearAllfields(self.req.addContact); //置空字段
            //dropdown clear
            $('#validateModalContact .dropdown').dropdown('clear');
        },
        //添加联系人弹窗保存
        saveContact:function(){
            var self = this;

            //联系人验证
            if(!!Customer.checkform('#validateModalContact')){
                return false;
            }

            var id = self.custItemStorage.custId;
            var birthday = $('#modal_contact_birthday').val();
            Vue.set(self.req.addContact,'custId',id);
            Vue.set(self.req.addContact,'birthday',birthday);
            axios.post(Customer.interface.addOrUpdateContact,self.req.addContact).then(function(response){
                var data = response.data;
                if(data.code == 0){
                    layer.msg('添加成功',{time:1000});
                    // self.updateContacts(id);
                    self.upposition({
                        id: data.data.id,
                        contactName: self.req.addContact.contactName,
                        contactNumber: self.req.addContact.phoneNumber
                    })
                }else{
                    layer.msg(data.code,{time:1000})
                }
                self.modal.contact = false;
            })
        },
        //更新联系人
        updateContacts:function(id){
            var self = this;
            //获取当前客户联系人系列
            Customer.axiosRequest(Customer.interface.contactInfo,{
                custId: id,
                types: 0 //0：意向，1:签约 2 潜在
            },function(result){
                if(result.code == 0){
                    self.queryContacts.result = result.data
                }
            },{
                type:'post'
            });
        },
        //添加跟进记录
        addFollowRecords:function(){
            /**
             * 请求配置项
             */
            var self=this;
            var url = Customer.interface.addOrUpdateFollowRecords;

            //时间处理
            var followTime = $('#followTime').val();
            self.followInfo.followTime = followTime;
            //获取跟进人id集合
            self.followInfo.followIds = [];
            for(var i =0; i<self.$store.state.selectedEmployees.length;i++){
                var item = self.$store.state.selectedEmployees[i]
                self.followInfo.followIds.push(item['id'])
            }
            //获取对接人id集合
            self.followInfo.custConcats = [];
            for(var i =0; i<self.followInfo.selectedContactInfo.length;i++){
                var item = self.followInfo.selectedContactInfo[i]
                self.followInfo.custConcats.push(item['id'])
            }

            //验证-S
            var validateObj = self.followInfo;
            var validateParam = {
                'followIds': {
                    msg: '请选择跟进人',
                },
                'followTime': {
                    msg: '请输入跟进时间',
                },
                'followType': {
                    msg: '请选择跟进方式',
                },
                'followReasonId': {
                    msg: '请选择跟进事由',
                },
                'custConcats': {
                    msg: '请选择客户对接人',
                },
                'followDetail': {
                    msg: '请填写跟进详情',
                },
            };
            if(!Customer.validate(validateObj,validateParam)){
                return false;
            }
            //验证-E


            //去掉-1,{},''
            var param = {};
            var originObj = self.followInfo;
            for(var index in originObj) {
                if (originObj.hasOwnProperty(index)) {
                    if (JSON.stringify(originObj[index]) !== '{}' && originObj[index] !== '' && originObj[index] !== -1 && originObj[index] != null  ) {
                        param[index] = originObj[index]
                    }
                }
            }
            // selectedContactInfo
            //提交跟进记录数据
            axios.post(url, param).then(function (response) {
                var data = response.data;
                if(data.code == 0){
                    self.modal.followRecord = false
                    layer.msg('添加成功！',{time:1000})
                    //渲染
                    self.renderFollowRecords(Customer.interface.followRecords,self.followPage.filterParameters)
                }else{
                    layer.msg(data.msg,{time:1000})
                }
            })

        },
        //弹窗清空
        clearAllfields:function(obj){
            var self = this;
            for(var i in obj){
                if(obj.hasOwnProperty(i)){
                    //特殊场景
                    if(i == 'gender' || i == 'gongLiFlag'){obj[i] = 0; continue}
                    if(i == 'intentionType' || i == 'types' || i == 'contactType'){continue}
                    //
                    var type = Object.prototype.toString.call(obj[i]).slice(8,-1);
                    switch(type){
                        case 'Array':
                            obj[i] = []
                            break
                        case 'String':
                            obj[i] = ''
                            break
                        case 'Number':
                            obj[i] = obj[i] === -1 ? -1: 0
                            break
                    }
                }
            }
        },
        //编辑+详情
        handleContent:function(id,handleType){
            /**
             * @handleType    0: 详情   1:编辑
             */
            var self = this;
            self.sLoading = true; //loading
            self.handle.state = handleType;
            self.handle.display = true; //显示操作页面
            //意向详情获取企业id
            Customer.axiosRequest(Customer.interface.intentionDetail,{id:id},function(result){
                if(result.code == 0){
                    var item = result.data;
                    self.custItemStorage = item; //暂存客户资料
                    self.intentionLabel(0); //加载业务标签
                    self.handle.data.intentionContent.custId = item.custId; //客户ID
                    self.handle.data.intentionContent.custQueryId = item.custQueryId; //客户企查查记录id
                    self.handle.data.intentionContent.customerType = item.customerType; //客户类型
                    self.handle.data.intentionContent.customerName = item.customerName; //客户名称
                    self.handle.data.intentionContent.gender = item.gender; //性别
                    self.handle.data.intentionContent.contactName = item.contactName; //联系人
                    self.handle.data.intentionContent.contactId = item.contactId; //联系人ID
                    self.handle.data.intentionContent.contactPhone = item.contactPhone; //联系电话
                    self.handle.data.intentionContent.provinceCode = item.provinceCode; //省编码
                    self.handle.data.intentionContent.cityCode = item.cityCode; //市编码
                    self.handle.data.intentionContent.countyCode = item.countyCode; //区编码
                    //对后台（区）传null处理
                    if(item.countyName == null){
                        item.countyName = '';
                        self.handle.data.intentionContent.citypickerAddress = item.provinceName + '/' + item.cityName; //后台返回省市地址
                    }else{
                        self.handle.data.intentionContent.citypickerAddress = item.provinceName + '/' + item.cityName + '/' + item.countyName; //后台返回省市区地址
                    }
                    self.handle.data.intentionContent.detailAddr = item.detailAddr; //详细地址
                    self.handle.data.intentionContent.custIntentionDetail = item.custIntentionDetail; //客户意向
                    self.handle.data.intentionContent.intentionTime = item.intentionTime; //创建时间
                    self.handle.data.intentionContent.createUserName = item.createUserName; //创建人

                    //请求意向标签接口
                    axios.get(Customer.interface.intentionLabel).then(function (response) {
                        //获取意向标签
                        self.handle.data.intentionContent.businessTags=response.data.data
                        for(var i=0;i<self.handle.data.intentionContent.businessTags.length;i++){
                            self.handle.data.intentionContent.tagAttribute[i] = false
                        }
                        //根据后台返回数据选中业务标签
                        var wholeTags = self.handle.data.intentionContent.businessTags;
                        if(item.businessLabelIds && wholeTags.length > 0){
                            var selectedArr = item.businessLabelIds.split(',');
                            for(var i = 0;i<wholeTags.length;i++){
                                var id = wholeTags[i]['id'];
                                for(var j=0;j<selectedArr.length;j++){
                                    if(id == selectedArr[j]){
                                        self.handle.data.intentionContent.tagAttribute[i] = true;
                                        break
                                    }
                                }
                            }
                        }
                    })
                    //跟进记录渲染
                    self.followPage.filterParameters.id = item.custId;
                    self.renderFollowRecords(Customer.interface.followRecords,self.followPage.filterParameters);
                    //指派记录渲染
                    self.assignPage.filterParameters.id = item.id;
                    self.renderAssignRecords(Customer.interface.assignRecords,self.assignPage.filterParameters);
                    //获取当前客户联系人
                    Customer.axiosRequest(Customer.interface.contactInfo,{
                        custId: self.custItemStorage.custId,
                        types: 0 //0：意向，1:签约 2 潜在
                    },function(result){
                        if(result.code == 0){
                            self.contactsData = result.data;
                        }
                    },{
                        type:'post'
                    });
                    self.$nextTick(function(){
                        $('.ui.checkbox').checkbox();
                        $('#edit_city2').citypicker();
                        //重新调一次时间组件
                        wzERP.Common.singleDate('.single-date');
                        //remove loading
                        setTimeout(function(){
                            self.sLoading = false;
                        },100)
                    })
                    //初始化富文本插件(放最后)
                    if(handleType == 1){ //编辑页面调用
                        var nodeName = document.getElementById('editor_edit').nodeName.toLowerCase();
                        if(self.isFirstCreateUE || nodeName == 'script'){
                            self.ue_edit = {}
                            self.ue_edit = UE.getEditor('editor_edit',{
                                autoFloatEnabled:false,
                            });
                            self.isFirstCreateUE = false;
                        }
                        self.ue_edit.ready(function(){
                            self.ue_edit.setContent(item.custIntentionDetail); //编辑富文本
                        })
                    }

                }else{
                    layer.msg(result.msg,{time:1000})
                }
            },{
                type:'post'
            });
        },
        //切换
        toggleDisplay:function(vObj){
            var display = vObj.display;
            Vue.set(vObj,'display',!display);
        },
        //业务限制人数
        limitedNum:function(selectedNum,id){
            /*Arg Guide
             @ selectedNum 已选择的人数
             @ id 点击的员工id
             */
            var self = this;
            var followLimited = 5; //跟进记录限制5个人
            var assignLimited = 3; //指派限制3个人

            var selectedEmployees = self.selectedEmployees;

            if(self.modal.followRecord == true && selectedEmployees.indexOf(id) == -1 && selectedNum >= followLimited ){
                layer.msg('限制'+followLimited+'个人',{time:1000})
                return false
            }else if(self.modal.assign == true && selectedEmployees.indexOf(id) == -1 && selectedNum >= assignLimited ){
                layer.msg('限制'+assignLimited+'个人',{time:1000})
                return false
            }else{
                return true
            }
        },
        //批量删除
        batchDelete:function(){
            var self = this;
            var batchIds = self.checkedCustIds;
            if(batchIds.length == 0){
                layer.msg('至少选择一个客户',{time:1000});
                return false
            }
            layer.alert('确定删除吗？', {
                title: '提示信息',
                btn: ['取消', '确认'],
                btn1:function(index){
                    layer.close(index)
                },
                btn2:function(){
                    self.sLoading = true;
                    axios({
                        method:'post',
                        url: Customer.interface.deleteBatchIntention,
                        data: JSON.stringify(batchIds),
                        headers: {
                            'Content-type': 'application/json'
                        }
                    }).then(function(response){
                        //remove loading
                        self.sLoading = false;
                        var data = response.data;
                        if(data.code == 0){
                            layer.msg('删除成功！',{time:1000});
                            self.renderMain(Customer.interface.intentionRecords,self.filterParameters);
                            self.checkAll = false;
                        }else{
                            layer.msg(data.msg,{time:1000})
                        }
                        self.checkedCustIds = [];
                    })
                }
            })
        },
        //添加意向客户名称blur
        blurDealResults:function(){
            var self = this;
            if(!self.queryEnterprise.result.hasResult){
                self.queryEnterprise.display = false;
            }
        },
        //返回主页
        returnToMain:function(){
            var self = this;
            self.handle.display = false;
        },
    }
})